<template>
  <div class="file-print">
    <el-form ref="postForm" :rules="rules" :model="postForm" class="form-container">
      <el-form-item label-width="120px" class="postInfo-container-item" label="任务名称" prop="title">
        <el-input v-model="postForm.title" :rows="1" type="textarea" class="article-textarea" autosize
          placeholder="输入任务名称" />
        <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}个</span>
      </el-form-item>

      <el-form-item label-width="120px" prop="content" class="postInfo-container-item" label="详细说明">
        <Tinymce ref="editor" v-model="postForm.body" :height="250" />
      </el-form-item>
      <el-form-item label-width="120px" label="上报类型" class="postInfo-container-item">
          <el-select v-model="postForm.data_type" placeholder="请选择上报类型" @change="selectReportType">
              <el-option label="通知" value="通知"></el-option>
              <el-option label="文件上传" value="文件上传"></el-option>
              <el-option label="表格填报" value="表格填报"></el-option>
              <el-option label="测评问卷" value="测评问卷"></el-option>
            </el-select>
      </el-form-item>
      <el-form-item label-width="120px" label="任务类别" class="postInfo-container-item" prop="classify">
        <el-select v-model="postForm.classify" placeholder="请选择任务类别">
          <el-option v-for="item in classifyOpt" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label-width="120px" label="紧急程度" class="postInfo-container-item" prop="emergency_level">
        <el-select v-model="postForm.emergency_level" placeholder="请选择紧急程度">
          <el-option label="紧急" value="紧急"></el-option>
          <el-option label="重要" value="重要"></el-option>
          <el-option label="常规" value="常规"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label-width="120px" class="postInfo-container-item" label="截止时间" prop="end_time">
        <el-date-picker v-model="postForm.end_time" type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="截止时间" />
        <!-- <span>结束时间到期后，将无法上传文件</span> -->
      </el-form-item>
      <el-form-item label-width="120px" label="附件">
        <file-check ref="upload" @changeFiles="changeFiles" :preview="true" :preFileList="preFileList"></file-check>
      </el-form-item>
    </el-form>
    <div class="subform">
      <el-button type="primary" size="small" @click="handSubmit">提交</el-button>
    </div>
    <div class="dialog" v-show="isShowDialog">
      <div class="content">
        <div class="text">文件上传进度</div>
        <el-progress :percentage="uploadPress" :stroke-width='10' class="process"></el-progress>
      </div>
    </div>
  </div>
</template>
<script>
  import Tinymce from '@/components/Tinymce'

  import {
    getTaskInfo,
    getTaskClassify
  } from '@/api/work.js'
  import {
    parseTime,
    fileJoinBaseUrl
  } from '@/utils/index'

  import axios from 'axios'
  import Cookies from 'js-cookie'

  export default {
    name: 'FilePrint',
    components: {
      Tinymce,
      FileCheck: () => import("@/views/markSys/components/FileCheck")
    },
    computed: {
      contentShortLength() {
        return this.postForm.title.length
      }
    },
    data() {
      return {
        postForm: {
          title: '',
          body: '',
          end_time: '',
          classify: '',
          emergency_level: '常规',
          is_approval: true,
          data_type: '文件上传'
        },
        isEdit: false,
        taskId: null,
        isShowDialog: false,
        preFileList: [], // 编辑时默认文件列表 
        fileList: [],
        uploadPress: 0,
        taskClassifyOpt: [],
        classifyOpt: [],
        taskClassify: [],
        noticeClassify: [],
        preFileList: [], // 已上传文件记录
        rules: {
          title: [{
              required: true,
              message: '请输入任务标题',
              trigger: 'blur'
            },
            {
              min: 4,
              message: '长度不能小于4个字符',
              trigger: 'blur'
            }
          ],
          classify: [{
            required: true,
            message: '请选择任务类别',
            trigger: 'blur'
          }],
          emergency_level: [{
            required: true,
            message: '请选择任务紧急程度',
            trigger: 'blur'
          }],
          end_time: [{
            required: true,
            message: '请选择任务截止时间',
            trigger: 'blur'
          }],
        }
      }
    },
    mounted() {
      const taskId = this.$route.query && this.$route.query.taskId
      if(taskId) {
        // taskId有值 则为材料审批任务编辑，填充任务信息
        this.isEdit = true
        this.taskId = taskId
        this.fetchTaskInfo(taskId)
      }
      this.requestTaskClassify()
    },
    methods: {
      // 提交创建任务请求
      handSubmit() {
        if (!this.postForm.body) {
          this.$message({
            type: 'warning',
            message: '请填写任务详细说明!'
          });
          return
        }
        this.$refs.postForm.validate(valid => {
          if (valid) {
            this.$confirm('即将提交任务数据, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(async () => {
              var form = new FormData()
              this.postForm['end_time'] = parseTime(this.postForm['end_time'])
              for (const key of Object.keys(this.postForm)) {
                if (key !== 'file') {
                  form.append(key, this.postForm[key])
                }
              }
              if (this.fileList.length > 0) {
                for (let i = 0; i < this.fileList.length; i++) {
                  form.append('file', this.fileList[i].raw)
                }
              }
              var config = {
                headers: {
                  'Content-Type': 'multipart/form-data',
                  'X-CSRFToken': Cookies.get('csrftoken')
                },
                onUploadProgress: progressEvent => {
                  var complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
                  this.uploadPress = Number(complete)
                }
              }

              if (this.fileList.length) {
                this.isShowDialog = true
              }
              if (this.isEdit) {
                axios.patch(`/api/Work/Task/${this.taskId}/`,
                  form, config).then((res) => {
                  this.uploadPress = 0
                  if (res.data) {
                    this.$notify({
                      title: '成功',
                      message: `编辑任务成功`,
                      type: 'success'
                    });
                    this.$router.push({
                      path: '/task-center/manager'
                    })
                  }
                  this.isShowDialog = false
                }).catch(res => {
                  this.isShowDialog = false
                });
              } else {
                axios.post(`/api/Work/Task/`,
                  form, config).then((res) => {
                  this.uploadPress = 0
                  if (res.data) {
                    this.$notify({
                      title: '成功',
                      message: `创建任务成功`,
                      type: 'success'
                    });
                    this.$router.push({
                      path: '/task-center/manager'
                    })
                  }
                  this.isShowDialog = false
                })
              }
            });
          }
        })
      },
      // 文件选择组件
      changeFiles(val) {
        this.fileList = val
      },
      selectReportType(val){
        // 如果类型是通知 选择noticeClassify
        if(val === '通知') {
          this.classifyOpt = this.noticeClassify
        }else{
          this.classifyOpt = this.taskClassify
        }
        // 默认选择第一个
        this.postForm.classify = this.classifyOpt[0] && this.classifyOpt[0].id
      },
      // 请求上报类型下拉框数据
      async requestTaskClassify() {
        const { data } = await getTaskClassify()
        const classifyList = data.results
        const taskClassify = classifyList.filter(item => item.type === 'task')
        const noticeClassify = classifyList.filter(item => item.type === 'notice')
        this.taskClassify =  taskClassify
        this.noticeClassify = noticeClassify
        // 默认加载通知 任务类别
        this.classifyOpt = taskClassify
        // 默认选择第一个
        this.postForm.classify = taskClassify[0] && taskClassify[0].id
      },
      // 请求任务信息
      async fetchTaskInfo(taskId) {
        const { data } = await getTaskInfo(taskId)
        const { title, body, classify, data_type, emergency_level, end_time, taskFile } = data
        this.postForm = {
          title, 
          body, 
          classify, 
          data_type, 
          emergency_level, 
          end_time
        }
        this.preFileList = fileJoinBaseUrl(taskFile) // 任务附件文件列表
        // 根据上报类型加载任务类别
        if(data_type === '通知') {
          this.classifyOpt = this.noticeClassify
        }else{
          this.classifyOpt = this.taskClassify
        }
      }
    },
  }

</script>
<style lang="scss">
  .file-print {
    position: relative;
    padding: 10px 50px 0;
    margin-bottom: 50px;
    .postInfo-container-item {
      margin-bottom: 20px;

      .editor-custom-btn-container {
        display: none;
      }
    }

    .word-counter {
      width: 40px;
      position: absolute;
      right: 10px;
      top: 0px;
    }

    .el-input__inner {
      width: 350px !important;
    }
    .article-textarea /deep/ {
      textarea {
        padding-right: 40px;
        resize: none;
        border: none;
        border-radius: 0px;
        border-bottom: 1px solid #bfcbd9;
      }
    }
    .subform{
        display: flex;
        justify-content: center;
    }
    .dialog {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, .5);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 999;
  
      .content {
        width: 300px;
        height: 80px;
        background: #fff;
  
        .text {
          text-align: center;
          padding: 10px 0;
        }
  
        .process {
          margin-left: 20px;
        }
      }
    }
  }


</style>
